import 'package:bruno/bruno.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../AppConfig/Config.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../l10n/messages.dart';

class DepositManagement extends StatefulWidget {
  const DepositManagement({super.key});

  @override
  State<DepositManagement> createState() => _DepositManagementState();
}

class _DepositManagementState extends State<DepositManagement> {
  String timeTitle="不限时间";
  List moneyTypeList=["全部","待转入您的钱包","待退还"];
  List orderTimeList=["2023-03-02 16:40","2023-03-03 16:40"];
  int chooseType=-1;
  int chooseTime=-1;
  Map depositMap={};
  List depositList=[];
  int pageNum=1;
  String timeStart="";
  String timeEnd="";
  String depositType="";
  String status="";
@override
  void initState() {
    // TODO: implement initState
    super.initState();
    getDepositMoney();
    getDepositList();
  }
  void _onRefresh(){
    pageNum=1;
    getDepositList();
  }
  void onReachBottom(){
    pageNum=pageNum+1;
    getDepositList();
  }
  void getDepositMoney(){
    NoLoadinggetApiManager.getData(
      context,
      "api/pay/deposit/bill/driverStatistic",
      {},
          (responseData)  {
        setState(() {

          depositMap=responseData['data'];
        });

      },
    );
  }
  void getDepositList(){
    NoLoadinggetApiManager.getData(
      context,
      "api/pay/deposit/bill/driverPage",
      {
        "current":pageNum,
        "size":20,
        "periodFrom":timeStart,
        "periodTo":timeEnd,
        "status":status,
        "depositType":depositType,

      },
          (responseData)  {
        setState(() {
         if(pageNum==1){
            depositList=responseData['data']['records'];
          }else {
           if(responseData['data']['records'].isNotEmpty){
             depositList.addAll(responseData['data']['records']);
           }else{
             setState(() {
               pageNum=pageNum-1;
             });

           }
          }

        });

      },
    );
  }
  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(messages['订金管理'],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
      ),
      body: ListView(
        children: [
          Container(
            padding: EdgeInsets.only(left: 20.w,right: 20.w,top: 15.h,bottom: 15.h),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [MyColors.themeColor, Color.fromRGBO(255,206,89,1)],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("担保中订金",style: TextStyle(fontSize: 12.sp,fontWeight: FontWeight.w600,color: Colors.white),),
                Text("¥"+depositMap['totalAmount'].toString(),style: TextStyle(fontSize: 20.sp,fontWeight: FontWeight.w600,color: Colors.white),),
                SizedBox(height: 8.h,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      width:140.w,
                      padding: EdgeInsets.only(left: 6.w,right: 6.w,top: 4.h,bottom: 4.h),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(6)),
                        color: Colors.white,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("可退订金",style: TextStyle(color: Colors.black,fontSize:12.sp ),),
                          SizedBox(height: 4.h,),
                          Text("¥"+depositMap['refundAmount'].toString(),style: TextStyle(fontSize: 16.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),
                        ],
                      ),
                    ),
                    Container(
                      width:140.w,
                      padding: EdgeInsets.only(left: 6.w,right: 6.w,top: 4.h,bottom: 4.h),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(6)),
                        color: Colors.white,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("不可退订金",style: TextStyle(color: Colors.black,fontSize:12.sp ),),
                          SizedBox(height: 4.h,),
                          Text("¥"+depositMap['unRefundAmount'].toString(),style: TextStyle(fontSize: 16.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 8.h,),
          Row(
            children: [
              SizedBox(width: 10.w,),
              GestureDetector(
                child:   Container(
                  padding: EdgeInsets.only(top: 4.h,bottom: 4.h,left: 4.w,right: 4.w),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(6)),
                    color: Colors.white,
                  ),
                  child: Row(
                    children: [
                      Text(chooseTime==-1? timeTitle:timeTitle,style: TextStyle(color: Colors.black),),
                      Icon(Icons.keyboard_arrow_down,color: MyColors.authTipColor,),
                    ],
                  ),
                ),
                onTap: ()async{
                  final result= await showModalBottomSheet(
                    context: context,
                    builder: (BuildContext context) {
                      return dataTimeSheet(type: 1,
                      );
                    },
                  );
                  if (result != null) {

                    setState(() {
                      timeTitle=result;
                      int indexOfZhi = result.indexOf("至");
                      timeStart= result.substring(0, indexOfZhi);
                      timeEnd= result.substring(indexOfZhi + 1);
                      pageNum=1;
                      getDepositList();
                    });
                  }
                },
              ),
              SizedBox(width: 8.w,),
              GestureDetector(
                child:   Container(
                  padding: EdgeInsets.only(top: 4.h,bottom: 4.h,left: 4.w,right: 4.w),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(6)),
                    color: Colors.white,
                  ),
                  child: Row(
                    children: [
                      Text(chooseType==-1?moneyTypeList[0]: moneyTypeList[chooseType-1],style: TextStyle(color: Colors.black),),
                      Icon( Icons.keyboard_arrow_down,color: MyColors.authTipColor,),
                    ],
                  ),
                ),
                onTap: (){
                  showModalBottomSheet(
                      context: context, builder: (BuildContext context) {
                    return Container(
                      padding: EdgeInsets.only(top: 15.h,bottom: 15.h,left: 10.w,right: 10.w),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                        color: Colors.white,
                      ),
                      height: 150.h,
                      width: screenSize.width,
                      child: Column(
                        children: [
                          GestureDetector(
                            child:  Text(moneyTypeList[0],style: TextStyle(color:chooseType==1?MyColors.themeColor: Colors.black,fontSize: 14.sp),),
                            onTap: (){
                              setState(() {
                                chooseType=1;
                                depositType="";
                                status="";
                              });
                              Navigator.pop(context);
                              pageNum=1;
                              getDepositList();
                            },
                          ),
                          SizedBox(height: 10.h,),
                          Container(height: 1.h,color: MyColors.backgreyColor,),
                          SizedBox(height: 10.h,),
                          GestureDetector(
                            child:  Text(moneyTypeList[1],style: TextStyle(color:chooseType==2?MyColors.themeColor: Colors.black,fontSize: 14.sp),),
                            onTap: (){
                              setState(() {
                                chooseType=2;
                                depositType="1";
                                status="1";
                              });
                              Navigator.pop(context);
                              pageNum=1;
                              getDepositList();
                            },
                          ),
                          SizedBox(height: 10.h,),
                          Container(height: 1.h,color: MyColors.backgreyColor,),
                          SizedBox(height: 10.h,),
                          GestureDetector(
                            child:  Text(moneyTypeList[2],style: TextStyle(color:chooseType==3?MyColors.themeColor: Colors.black,fontSize: 14.sp),),
                            onTap: (){
                              setState(() {
                                chooseType=3;
                                depositType="0";
                                status="1";
                              });
                              Navigator.pop(context);
                              pageNum=1;
                              getDepositList();
                            },
                          ),
                        ],
                      ),
                    );
                  }
                  );
                },
              ),
            ],
          ),
          SizedBox(height: 8.h,),
    EasyRefresh(
    header:
    ClassicHeader(
    dragText: '下拉刷新',
    armedText: '准备释放',
    readyText: '加载中...',
    processingText: '加载中...',
    processedText: '刷新成功',
    noMoreText: '暂无更多',
    failedText: '刷新失败',
    messageText: '刷新时间 %T',
    ),
    footer: ClassicFooter(
    dragText: '加载更多',
    armedText: '准备释放',
    readyText: '加载中...',
    processingText: '加载中...',
    processedText: '加载成功',
    noMoreText: '暂无更多',
    failedText: '加载失败',
    messageText: '加载时间 %T',
    ),
    onRefresh: _onRefresh,
    onLoad:depositList.length>20*pageNum-1?onReachBottom:null,
    child:
          Container(
            margin: EdgeInsets.only(left: 10.w,right: 10.w),
            height: screenSize.height-280.h,
            child:ListView.builder(
                itemCount: depositList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    margin: EdgeInsets.only(bottom: 8.h),
                    padding: EdgeInsets.only(left: 8.w,top: 10.h),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      color: Colors.white,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(depositList[index]['shipperName'],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                            Row(
                              children: [
                                if(depositList[index]['depositType']==1)
                                BrnTagCustom.buildBorderTag(
                                  tagText: '不退还',
                                  textColor: Colors.green,
                                  borderColor:Colors.green,
                                  borderWidth: 1,
                                  backgroundColor:Color.fromRGBO(
                                      130, 240, 105, 0.26666666666666666),
                                  fontSize: 10.sp,
                                ),
                                if(depositList[index]['depositType']==0)
                                  BrnTagCustom.buildBorderTag(
                                    tagText: '可退',
                                    textColor: MyColors.themeColor,
                                    borderColor: MyColors.themeColor,
                                    borderWidth: 1,
                                    backgroundColor:Color.fromRGBO(251, 236, 228, 1),
                                    fontSize: 10.sp,
                                  ),
                                SizedBox(width: 4.w,),
                                Text("¥"+depositList[index]['amount'],style: TextStyle(color: MyColors.themeColor,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                                SizedBox(width: 8.w,),
                              ],
                            ),

                          ],
                        ),
                        SizedBox(height: 4.h,),
                        Text("支付时间"+" "+depositList[index]['createTime'],style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                        SizedBox(height: 4.h,),
                        Text(depositList[index]['productDesc'],style: TextStyle(color: Colors.black,fontSize: 12.sp),),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [ BrnTagCustom(
                            tagText: depositList[index]['productDesc']==1?"支付到平台":depositList[index]['productDesc']==2?'货主已退还':depositList[index]['productDesc']==3?"支付到货主":"未支付",
                            textColor: Colors.black,
                            fontSize: 12.sp,
                            textPadding: EdgeInsets.only(left: 8.w,right: 8.w,top: 4.h,bottom: 4.h),
                            backgroundColor:Color.fromRGBO(251, 236, 228, 0.45),
                            tagBorderRadius: BorderRadius.only(bottomRight: Radius.circular(10),topLeft: Radius.circular(10) ),
                          ),
                          ],
                        ),
                      ],
                    ),
                  );
                }),
          )
    ),
        ],
      ),
    );
  }
}
class dataTimeSheet extends StatefulWidget {
  const dataTimeSheet({super.key, required this.type});
  final int type;
  @override
  State<dataTimeSheet> createState() => _dataTimeSheetState();
}

class _dataTimeSheetState extends State<dataTimeSheet> {
  DateTime selectedDate = DateTime.now();
  int selectedYear = DateTime.now().year;
  int selectedMonth = DateTime.now().month;
  int selectedDay = DateTime.now().day;
  int selectedHour = DateTime.now().hour;
  late List<int> years;
  late FixedExtentScrollController yearController;
  late FixedExtentScrollController monthController;
  late FixedExtentScrollController dayController;
  late FixedExtentScrollController hourController;
  String startTime ="${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day}";
  String endTime ="";
  int timeType=1;
  @override
  void initState() {
    super.initState();

    DateTime selectedDate = DateTime.now();
    int selectedYear = DateTime.now().year;
    int selectedMonth = DateTime.now().month;
    int selectedDay = DateTime.now().day;
    int selectedHour = DateTime.now().hour;
    int currentYear = DateTime.now().year;
    years = List.generate(6, (index) => currentYear + index);
    // 设置初始滚动位置
    yearController = FixedExtentScrollController(initialItem: years.indexOf(selectedYear));
    monthController = FixedExtentScrollController(initialItem: selectedMonth - 1);
    dayController = FixedExtentScrollController(initialItem: selectedDay - 1);
    hourController = FixedExtentScrollController(initialItem: selectedHour);
  }
  @override
  int getDaysInMonth(int year, int month) {
    return DateTime(year, month + 1, 0).day;
  }

  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 10.w,bottom: 40.h),
        height: 330.h,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10)),
          color: Colors.white,
        ),
        child:Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(onPressed: (){
                  Navigator.pop(context);
                }, child: Text("取消",style: TextStyle(color: Colors.black,fontSize: 14.sp),)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.access_time,color: MyColors.textColor,),
                    Text("选择时间",style:TextStyle(color: Colors.black,fontSize: 16.sp),),
                  ],
                ),

                TextButton(onPressed: (){

                  if(startTime==""){
                    BrnToast.show("请选择开始时间", context);
                  }else if(endTime==""){
                    BrnToast.show("请选择结束时间", context);
                  }else if(DateTime.parse(endTime).difference(DateTime.parse(startTime)).inDays>31 ){
                    BrnToast.show("最长可查询时间跨度31天的数据", context);
                  }else{

                    Navigator.pop(context,startTime+"至"+endTime);
                  }

                }, child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp))),
              ],
            ),
            Text("最长可查询时间跨度31天的数据",style: TextStyle(color: MyColors.themeColor,fontSize: 11.sp),),
            Divider(height: 16.h,color: MyColors.backgreyColor,),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(width: 10.w,),
                GestureDetector(
                  child:  Column(
                    children: [
                      Text(startTime==""?"开始时间":startTime,style: TextStyle(color:timeType==1?MyColors.themeColor: Colors.black,fontSize: 13.sp),),
                      Container(
                        height: 2.h,width:20.w,
                        color:timeType==1? MyColors.themeColor:Colors.white,
                      )
                    ],
                  ),
                  onTap: (){
                    setState(() {
                      timeType=1;
                    });
                  },
                ),

                Text("至",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                GestureDetector(
                  child: Column(
                    children: [
                      Text(endTime==""?"结束时间":endTime,style: TextStyle(color: timeType==2?MyColors.themeColor: Colors.black,fontSize: 13.sp),),
                      Container(
                        height: 2.h,width:20.w,
                        color:timeType==2? MyColors.themeColor:Colors.white,
                      )
                    ],
                  ),
                  onTap: (){
                    setState(() {
                      timeType=2;
                    });
                  },
                ),

                SizedBox(width: 10.w,),
              ],
            ),
            Divider(height: 16.h,color: MyColors.backgreyColor,),

            Text("时间格式:年-月-日",style: TextStyle(color: Colors.black),),
            SizedBox(height: 4.h,),
            Container(
              decoration: BoxDecoration(
                border: Border.all(
                  color: Color.fromRGBO(224, 227, 234, 1),
                  width: 1,
                ),
                borderRadius: BorderRadius.circular(5.0), // 可选，添加圆角
              ),
              child:  Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildPicker(
                    items: generateYearList(),
                    controller: yearController,
                    onChanged: (value) {
                      setState(() {
                        selectedYear = value;
                        timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')
                            :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0');
                      });
                    },
                  ),
                  _buildPicker(
                    items: List.generate(12, (index) => index + 1),
                    controller: monthController,
                    onChanged: (value) {
                      setState(() {
                        selectedMonth = value;
                        timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')
                            :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0');
                      });
                    },
                  ),
                  _buildPicker(
                    items: List.generate(getDaysInMonth(selectedYear, selectedMonth), (index) => index + 1),
                    controller: dayController,
                    onChanged: (value) {
                      setState(() {
                        selectedDay = value;
                        timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')
                            :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0');
                      });
                    },
                  ),
                  // _buildPicker(
                  //   items: List.generate(24, (index) => index),
                  //   controller: hourController,
                  //   onChanged: (value) {
                  //     setState(() {
                  //       selectedHour = value;
                  //       timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "
                  //           :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0');
                  //     });
                  //   },
                  // ),
                ],
              ),
            ),


          ],
        )



    );
  }
  Widget _buildPicker({
    required List<int> items,
    required FixedExtentScrollController controller,
    required ValueChanged<int> onChanged,
  }) {
    return Container(
      height: 150.0,
      width: 80.0,
      child: CupertinoPicker(
        itemExtent: 40.0,
        onSelectedItemChanged: (index) {
          onChanged(items[index]);
        },
        selectionOverlay: _buildSelectionOverlay(),
        children: items.map((item) => _buildPickerItem(item)).toList(),
        // 使用初始化的控制器
        scrollController: controller,
      ),
    );
  }

  Widget _buildPickerItem(int item) {
    // 将月份和日期格式化为两位数
    String formattedItem = item.toString().padLeft(2, '0');

    return Container(
      alignment: Alignment.center,
      child: Text(formattedItem),
    );
  }

  Widget _buildSelectionOverlay() {
    return Container(
      height: 40.0,
      decoration: BoxDecoration(
        border: Border(
          top: BorderSide(color: Color.fromRGBO(220, 224, 231, 1), width: 1.0.h),
          bottom: BorderSide(color: Color.fromRGBO(220, 224, 231, 1), width: 1.0.h),
        ),
      ),
    );
  }

  // 生成年份列表，包括当前年份和之后的5年
  List<int> generateYearList() {
    int currentYear = DateTime.now().year;
    List<int> years = List.generate(6, (index) => currentYear + index);
    return years;
  }
}